package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;
import com.xsherl.leetcode.utils.ArrayUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: sherl
 * @Date: 2021/5/24 20:54
 */
public class GenerateParenthesis {

    /**
     * 深度优先搜索（回溯）
     * 利用深度优先搜索，每次搜索都有两种方式
     *  1. 探索 ‘(’
     *  2. 探索 ‘)’
     *  一直探索到所有括号都用完为止
     * @param n
     *  1 <= n <= 8
     */
    public List<String> generateParenthesis(int n) {
        List<String> res = new LinkedList<>();
        dfs(new StringBuilder(), 0, 0, n, res);
        return res;
    }

    public void dfs(StringBuilder sb, int left, int right, int n, List<String> list){
        if (sb.length() == n * 2){
            list.add(sb.toString());
            return;
        }
        if (left < right){
            return;
        }

        if (left < n){
            dfs(sb.append("("), left + 1, right, n, list);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right < n){
            dfs(sb.append(")"), left, right + 1, n, list);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

    public static void main(String[] args) {
        int n = 3;
        List<String> strings = new GenerateParenthesis().generateParenthesis(n);
        System.out.println(strings);
        String[] output = ArrayUtils.parseArray("[\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]", String.class);
        Assert.isTrue(Arrays.asList(output).containsAll(strings));
    }

}
